package com.example.filter_interceptor_test.config;

import com.example.filter_interceptor_test.filter.Filter1;
import com.example.filter_interceptor_test.filter.Filter2;
import com.example.filter_interceptor_test.filter.Filter3;
import com.example.filter_interceptor_test.filter.Filter4;
import com.example.filter_interceptor_test.interceptor.Interceptor1;
import com.example.filter_interceptor_test.interceptor.Interceptor2;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Filter;
import java.util.Collections;

/**
 * @author sorata
 * @since 2023/2/1 22:39
 */
@Configuration(proxyBeanMethods = false)
public class Config implements WebMvcConfigurer {

    @Bean
    public FilterRegistrationBean<?> registrationBean(){
        FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setUrlPatterns(Collections.singleton("/*"));
        registrationBean.setFilter(new Filter1());
        registrationBean.setOrder(0);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean<?> registrationBean1(){
        FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setUrlPatterns(Collections.singleton("/api/v1/*"));
        registrationBean.setFilter(new Filter2());
        registrationBean.setOrder(-1);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean<?> registrationBean2(){
        FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setUrlPatterns(Collections.singleton("/api/v2/*"));
        registrationBean.setFilter(new Filter3());
        registrationBean.setOrder(1);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean<?> registrationBean3(){
        FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setUrlPatterns(Collections.singleton("/*"));
        registrationBean.setFilter(new Filter4());
        registrationBean.setOrder(2);
        return registrationBean;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        WebMvcConfigurer.super.addInterceptors(registry);
        registry.addInterceptor(new Interceptor1());
        registry.addInterceptor(new Interceptor2());
    }
}
